import tkinter as tk
from tkinter import ttk
from tkinter import font as tkfont
from user_client_socket import TcpSocket
from tkinter import messagebox as msgbox
import json
from setting import *
from datetime import date, timedelta
import re
import time
# effbot.org


# 主页页面, 进行了页面的初始化设置,设置其他页面的时候需要继承该页面
class IndexPage:
    def __init__(self,  width=750, height=450, page_name='Page_1'):

        self.width = width
        self.height = height
        self.pname = page_name
        self.STAND_RELX = .1
        self.STAND_RELY = .2
        self.window = tk.Tk()
        self.font = tkfont.Font(family='宋体', size=12, weight='normal')
        tkfont.Font()
        self.scree_size = '%dx%d+%d+%d' % (self.width, self.height, (self.window.winfo_screenwidth() - width) / 2,
                                           (self.window.winfo_screenheight() - height) / 2)
        self.window.geometry(self.scree_size)
        self.window.title(self.pname)
        self.us = TcpSocket()
        # self.cur = mysql()

        self.uname = '6666'
        self.pwd = ''

    def get_window(self):
        return self.window

    def create_page(self):

        def login_info_get(self):
            f1 = tk.LabelFrame(self.window, width=400, height=self.height)
            f2 = tk.LabelFrame(self.window, width=340, height=self.height)

            # 左侧图片
            pt = tk.PhotoImage(file='/home/tarena/aid1809/personal/online_education/咱们组的项目/test.gif')
            cav = tk.Canvas(self.window, height=10, width=10)
            cav.create_image(0, 0, image=pt)
            cav.place(relx=0, rely=0)

            STAND_RELX = .1
            STAND_RELY = .2
            tk.Label(f2, text='用户名:', font=self.font).place(relx=STAND_RELX, rely=STAND_RELY)
            tk.Label(f2, text='密  码:', font=self.font).place(relx=STAND_RELX, rely=STAND_RELY + .2)

            uname = tk.Entry(f2, font=self.font)
            uname.bind('<Return>', lambda x: self.keyboard_login(x, uname, pwd))
            uname.place(relx=STAND_RELX+.2, rely=STAND_RELY)

            pwd = tk.Entry(f2, font=self.font, width=20)
            pwd.bind('<Return>', lambda x: self.keyboard_login(x, uname, pwd))
            pwd.place(relx=STAND_RELX + .2, rely=STAND_RELY+.2)

            tk.Button(f2, text='登录', command=lambda: self.do_login(uname, pwd), font=self.font
                      ).place(relx=STAND_RELX+.15, rely=STAND_RELY*3)
            tk.Button(f2, text='注册', command=self.do_regist, font=self.font
                      ).place(relx=STAND_RELX+.6, rely=STAND_RELY*3)

            f1.grid(row=0, column=0, padx=10)
            f2.grid(row=0, column=1)

        login_info_get(self)
        self.window.mainloop()

    def do_find_pwd(self):
        self.window.destroy()
        first_find_page = FindPwdStepFirst()
        first_find_page.create_page()

    def do_regist(self):
        self.window.destroy()
        regist_page = RegistUser()
        regist_page.create_page()

    def keyboard_login(self, event, uname, pwd):
        print(event)
        self.do_login(uname, pwd)

    def do_login(self, user_name, passwd):
        # 获取用户名密码，然后去服务端对比，ok的话就quit这个然后打开新的页面
        # self.uname = user_name.get().strip()
        self.uname = 'wang'
        # self.pwd = passwd.get().strip()
        self.pwd = '1234'

        user_info_accept_msg = 'GET /tlogin?user_name=%s&passwd=%s HTTP/1.1' % (self.uname, self.pwd)
        self.us.send_to_server(user_info_accept_msg)
        recv_status = self.us.recv_from_server().split(':')
        # if self.uname == '':
        #     recv_status = ('200',)

        if recv_status[0] == '200':
            self.window.destroy()  # 这里只能用destroy,用quit()的话主界面就退不出去
            self.user_id = recv_status[2]
            home_page = HomePage(self.uname, self.user_id)
            home_page.create_page()

        elif recv_status[0] == '404':
            print(recv_status[0])

        else:
            print('什么都没有匹配到')


# 用户信息页面
class UserInfoPage(IndexPage):
    def __init__(self, user_name, user_id):
        super().__init__()
        self.uname = user_name
        self.uid = user_id

    def create_page(self):
        self.window.title('个人信息')
        uinfo_lf = tk.LabelFrame(height=self.height/2-10, width=self.width/2-10, text='用户信息')
        uifo2_lf = tk.LabelFrame(height=self.height/2-10, width=self.width/2-10, text='其他信息')
        uclass_lf = tk.LabelFrame(height=self.height/2-10, width=self.width/2-10, text='约课信息')
        uclass_detail = tk.LabelFrame(height=self.height/2-10, width=self.width/2-10, text='约课详情')

        # 用户信息块
        tk.Label(uinfo_lf, text='用户名： ', font=self.font).place(relx=self.STAND_RELX, rely=self.STAND_RELY)
        tk.Label(uinfo_lf, text=self.uname, font=self.font).place(relx=self.STAND_RELX+.1, rely=self.STAND_RELY)

        tk.Label(uinfo_lf, text='性别： ', font=self.font).place(relx=self.STAND_RELX, rely=self.STAND_RELY+.2)
        tk.Label(uinfo_lf, text='未设置', font=self.font).place(relx=self.STAND_RELX + .1, rely=self.STAND_RELY+.2)

        tk.Label(uinfo_lf, text='生日： ', font=self.font).place(relx=self.STAND_RELX, rely=self.STAND_RELY+.4)
        tk.Label(uinfo_lf, text='未设置', font=self.font).place(relx=self.STAND_RELX + .1, rely=self.STAND_RELY+.4)

        # 开启聊天
        c_lb = tk.Button(uclass_lf, command=self.do_chat)
        c_lb.place(relx=0, rely=0, relheight=1, relwidth=1)

        # 返回主页
        return_btn = tk.Button(uclass_detail, command=self.do_back)
        return_btn.place(relx=0, rely=0, relheight=1, relwidth=1)

        uinfo_lf.grid(row=0, column=0, padx=5, pady=5, sticky=tk.N)
        uifo2_lf.grid(row=1, column=0, padx=5, pady=5, sticky=tk.N)
        uclass_lf.grid(row=0, column=1, padx=5, pady=5)
        uclass_detail.grid(row=1, column=1, padx=5, pady=5)

        self.window.mainloop()
        # self.window.mainloop()

    def do_back(self):
        self.window.destroy()
        homepage = HomePage(self.uname, self.uid)
        homepage.create_page()

    def do_chat(self):
        self.window.destroy()
        replycomment = ReplyComment(self.uname, self.uid)
        replycomment.create_page()

        # ??????bug自我修复了？
        self.window.destroy()
        user_info = UserInfoPage(self.uname, self.uid)
        user_info.create_page()


    def do_return_home_page(self):
        self.window.destroy()
        home_page = BackToHome(self.uname)
        home_page.create_page()

    def class_cancel(self):
        pass


# 课程详情页面
class ClassDetail(IndexPage):
    def __init__(self, user_name):
        super().__init__()
        self.name = user_name

    def create_page(self):
        self.window. title('我是视频详情页面')
        self.window.mainloop()


# 主页面
class HomePage(IndexPage):
    def __init__(self, user_name, user_id):
        super().__init__()
        self.uname = user_name
        self.uid = user_id

    def create_page(self):
        # 页面元素构建
        self.window.title('我是主页')
        fb_height = 30

        # button栏
        fbutton = tk.Frame(self.window, height=fb_height, width=self.width)
        welcome_msg = '欢迎您回来:  %s' % self.uname
        lb = tk.Label(fbutton, text=welcome_msg, font=self.font, padx=20)
        lb.bind('<Button-1>', self.do_user_info_page)
        lb.place(relx=0, rely=0)
        tk.Button(fbutton, text='开课', height=1, width=7, command=self.do_class_order).place(relx=.9, rely=0)
        fbutton.grid(row=0, column=0)

        lf1 = tk.LabelFrame(self.window,
                            height=self.height-fb_height, width=self.width,
                            text='课程视频')

        lf1.grid(row=1, column=0)

        notebk = ttk.Notebook(lf1, width=self.width, height=self.height-20)
        print(notebk.winfo_height())
        type_item = ['数学', '语文']

        def create_tab(item, notebk):
            f = tk.Frame(notebk)

            lstb = tk.Listbox(f, height=self.height, width=self.height)
            lstb.insert(0, item)
            lstb.grid(row=0, column=0)

            notebk.add(f, text=item)
            return f

        for i in type_item:
            f = create_tab(i, notebk)

        # tk.Label(text=self.uname, font=self.font).place(x=int(self.width) * 0.8, y=int(self.height) * 0.1)
        # tk.Button(text='跳转到是视频详情页', command=self.play_movie, bg='white'
        #           ).place(x=int(self.width) * 0.8, y=int(self.height) * 0.2)
        # tk.Button(text='跳转到用户', command=self.do_user_info_page).pack(side='left')
        # tk.Button(text='开课', command=self.do_class_orderfo).pack(side='bottom')

        notebk.place(relheight=1, relwidth=1)
        # 页面开始循环
        self.window.mainloop()

    def do_class_order(self):
        self.window.destroy()
        # try:
        class_order = OrderPage(self.uname, self.uid)
        class_order.create_page()
        # except Exception as e:
        #     print('课程预约页面异常, 错误原因：', e)

    def do_user_info_page(self, _):
        self.window.destroy()
        user_info_page = UserInfoPage(self.uname, self.uid)
        user_info_page.create_page()

    def do_video_page(self):
        self.window.destroy()
        video_page = VideoPage(self.uname, self.uid)
        video_page.create_page()


# 视频详情页面
class VideoPage(IndexPage):
    def __init__(self, user_name, user_id):
        super().__init__()
        self.user_name = user_name
        self.uid = user_id

    def create_page(self):
        tk.Label(text='我是视频详情').pack(side='left')
        tk.Button(text='返回上一页', command=self.do_return_last_page).pack(side='right')
        self.window.mainloop()

    def do_return_last_page(self):
        self.window.destroy()
        home_page = HomePage(self.user_name, self.uid)
        home_page.create_page()


# 注册页面
class RegistUser(IndexPage):
    def __init__(self):
        super().__init__()
        self.window.title('我是注册页面')

    def create_page(self):
        f1 = tk.LabelFrame(self.window, text='注册信息', height=400, width=310)

        lb_name = tk.Label(f1, text='  用户名:', font=self.font)
        lb_pwd = tk.Label(f1, text='  密  码:', font=self.font)
        lb_again_pwd = tk.Label(f1, text='确认密码:', font=self.font)
        lb_email = tk.Label(f1, text='  邮  箱:', font=self.font)

        self.rg_user_name = tk.Entry(f1)
        self.rg_user_email = tk.Entry(f1)
        self.rg_user_passwd = tk.Entry(f1, show='*')
        self.rg_user_again_passwd = tk.Entry(f1, show='*')

        tk.Button(f1, text='提交', command=self.done_regist).place(relx=self.STAND_RELX+.05, rely=self.STAND_RELY+.5)
        tk.Button(f1, text='返回', command=self.do_back).place(relx=self.STAND_RELX+.55, rely=self.STAND_RELY+.5)

        # 控件pack()
        lb_name.place(relx=self.STAND_RELX, rely=self.STAND_RELY)
        lb_email.place(relx=self.STAND_RELX, rely=self.STAND_RELY+.1)
        lb_pwd.place(relx=self.STAND_RELX, rely=self.STAND_RELY+.2)
        lb_again_pwd.place(relx=self.STAND_RELX, rely=self.STAND_RELY+.3)

        self.rg_user_name.place(relx=self.STAND_RELX+.25, rely=self.STAND_RELY)
        self.rg_user_email.place(relx=self.STAND_RELX+.25, rely=self.STAND_RELY+.1)
        self.rg_user_passwd.place(relx=self.STAND_RELX+.25, rely=self.STAND_RELY+.2)
        self.rg_user_again_passwd.place(relx=self.STAND_RELX+.25, rely=self.STAND_RELY+.3)

        f1.grid(row=0, column=0, padx=220, pady=20)
        self.window.mainloop()

    def done_regist(self):
        # 用户名判断, 3种情况
        if self.rg_user_name.get() == '':
            msgbox.showinfo(title='新用户注册', message='注册的时候用户名为空你是要上天？')
            return

        if len(self.rg_user_name.get()) < 6:
            msgbox.showinfo(title='新用户注册', message='你这用户名也忒短了,人家得6-12位？')
            return

        comp = re.compile('[\W]')
        re_result = re.findall(comp, self.rg_user_name.get())
        if re_result:
            msgbox.showinfo(title='新用户注册', message='用户名就支持数字字母下划线,你看着办吧')
            return

        # 邮箱判断, 2种情况
        if self.rg_user_email.get() == '':
            msgbox.showinfo(title='新用户注册', message='不输邮箱密码忘了你怎么办？')
            return

        comp = re.search('([\S]+)(?P<domain>@\w+\.(com|cn|net))', self.rg_user_email.get().strip())
        if not comp:
            msgbox.showinfo(title='新用户注册', message='你邮箱域名格式这德行？')
            return

        # 密码判断, 2种情况
        comp = re.search('\s', self.rg_user_passwd.get())
        if comp :
            msgbox.showinfo(title='新用户注册', message='密码里带空格,怎么就你特殊呢？')
            self.rg_user_passwd.delete(0,100)
            return

        if self.rg_user_passwd.get() == '':
            msgbox.showinfo(title='新用户注册', message='我就问你没密码你怎么登录？啊？')
            return

        if self.rg_user_again_passwd.get() == '':
            msgbox.showinfo(title='新用户注册', message='单身这么多年的手速不怕输错？还不确认一遍？')
            return

        if self.rg_user_again_passwd.get() != self.rg_user_passwd.get():
            msgbox.showinfo(title='新用户注册', message='确认密码你确认了吗就往里填？')
            self.rg_user_again_passwd.delete(0,100)
            return

        regist_request = 'GET /regist/teacher?user_name=%s&passwd=%s&email=%s socket' % (
            self.rg_user_name.get(), self.rg_user_passwd.get(), self.rg_user_email.get())

        self.us.send_to_server(regist_request)
        regist_msg = self.us.recv_from_server().split(':')
        print(regist_msg)

        if regist_msg[0] == '200':
            print(regist_msg[1])
            msgbox.showinfo(title='新用户成功', message=regist_msg[1])
            self.window.destroy()
            index_page = IndexPage()
            index_page.create_page()
        else:
            print(regist_msg[1])
            msgbox.showinfo(title='新用户成功', message=regist_msg[1])

    def do_back(self):
        pass


# 找回密码第一页
class FindPwdStepFirst(IndexPage):
    def __init__(self):
        super().__init__()
        self.window.title('我是找回密码的第一个页面')

    def create_page(self):
        tk.Button(text='提交', command=self.go_find_pwd_second).pack()
        self.window.mainloop()

    def go_find_pwd_second(self):
        self.window.destroy()
        second_findpwd_page = FindPwdStepSecond()
        second_findpwd_page.create_page()


class FindPwdStepSecond(IndexPage):
    def __init__(self):
        super().__init__()
        self.window.title('我是找回密码的第二个页面')

    def create_page(self):
        tk.Button(text='提交修改', command=self.done_find_pwd).pack(side='right')
        self.window.mainloop()

    def done_find_pwd(self):
        # 判断设置的密码是否合法, 如果合法则执行下面的代码
        self.window.destroy()
        index_page = IndexPage()
        index_page.create_page()


class ReplyComment(IndexPage):
    def __init__(self, user_name, user_id):
        super().__init__()
        self.uname = user_name
        self.uid = user_id
        self.window.title('评论回复')

    def create_page(self):
        # frame设置
        comm_view = tk.LabelFrame(self.window, text='留言列表',
                                  height=self.height-20,
                                  width=self.width/2-20, )
        comm_detail = tk.LabelFrame(self.window, text='留言详情',
                                    height=self.height * .6,
                                    width=self.width/2-20)

        comm_view.grid(row=0, column=0, padx=10, pady=5, rowspan=3)
        comm_detail.grid(row=0, column=1, padx=10, pady=5, sticky=tk.N)

        comm_content = tk.LabelFrame(self.window, text='评论框', height=self.height*.2, width=self.width/2-20)
        comm_content .grid(row=1, column=1, padx=5, sticky=tk.N)

        # 留言预览:1.notebook 2.两个frame:已回复;未回复 3.frame里添加listbox
        nb = ttk.Notebook(comm_view)

        f1 = tk.Frame(nb)
        unread_tab = tk.Listbox(f1)
        nb.add(f1, text='未读留言')
        unread_tab.place(relx=0, rely=0, relwidth=1, relheight=1)

        f2 = tk.Frame(nb)
        read_tab = tk.Listbox(f2)
        nb.add(f2, text='已读留言')
        read_tab.place(relx=0, rely=0, relwidth=1, relheight=1)

        nb.place(relx=0, rely=0, relheight=1, relwidth=1)

        # 留言详情lb
        msg = '双击留言查看详情...'
        comm_detail_lb = tk.Text(comm_detail, bg='white')
        comm_detail_lb.insert(tk.END, msg)

        comm_detail_lb.place(relx=0, rely=0, relwidth=1, relheight=1)

        # 评论框
        comm_content_text = tk.Text(comm_content)

        # 发送评论按钮
        def do_comment(name):
            commr = comm_content_text.get(0.0, tk.END).strip()
            if commr == '':
                msgbox.showinfo(title='添加回复', message='没有填写回复信息哟')
                return

            msg = '\n来自:%s\n  %s' % (name, commr)

            comm_detail_lb.insert(tk.END, msg)

            try:
                index = unread_tab.curselection()[0]
            except IndexError:
                msgbox.showinfo(title='添加回复', message='留言没有被选中哟')
            else:
                comment_time = time.strftime('%Y%m%d%H%M%S')
                reply_comment(commr, comment_time, comm_id_mapped[index] )
                unread_tab.delete(index)
                comm_content_text.delete(0.0, tk.END)
                read_tab.insert(0,)

        tk.Button(text='添加回复', width=6, command=lambda: do_comment(self.uname)
                  ).grid(row=2, column=1, padx=10, sticky=tk.E)

        # 留言预览监听方法
        def view_choice(_):
            index = unread_tab.curselection()[0]
            print(index)
            coder, msgr = comment_detail[index]
            if coder == '200':
                comm_detail_lb.delete(0.0, tk.END)
                comm_detail_lb.insert(tk.END, msgr)
                comm_content_text.place(relx=0, rely=0, relwidth=1, relheight=1)
            elif coder == '500':
                msgbox.showinfo(title='回复评论', message=msgr)

        # 留言预览添加监听
        unread_tab.bind('<Double-Button-1>', view_choice)

        # 评论预览页面中添加数据
        self.us.send_to_server('GET /comment/teacher?teacher_id=%s socket' % self.uid)
        coder, msgr_json = self.us.recv_from_server().split(':', 1)
        msgr = json.loads(msgr_json)

        comment_detail = []  # 存储评论的详细内容
        comm_id_mapped = {}  # 存储索引和评论id的映射关系
        if coder == '500':
            msgbox.showinfo(title='评论获取', message='')
        index = 0
        for comment in msgr:
            msg_id = comment['comment_id']
            comm_content = comment['comment']
            stu_name = comment['stu_name']

            unread_tab.insert(index, comm_content)

            comment_detail.append('留言来自:%s\n  %s' % (stu_name, comm_content))
            comm_id_mapped[index] = msg_id

            index += 1

        # 已回复评论预览页面中添加数据
        def reply_comment(reply_msg, reply_time, cid):
            self.us.send_to_server('GET /comment/reply?reply_content=%s&reply_time=%s&reply_msg_id=%s socket'
                                   % (reply_msg, reply_time, cid))
            a = self.us.recv_from_server().split(':')
            print(a)

            if coder == '200':
                print('回复信息成功')
            else:
                msgbox.showinfo(title='回复留言', message='信息回复失败, 请稍后尝试')

        self.window.mainloop()


# 课程预约界面
class OrderPage(IndexPage):
    def __init__(self, user_name, user_id):
        self.var = tk.StringVar
        super().__init__()
        self.uname = user_name
        self.uid = user_id

    def create_page(self):
        width = self.width // 2
        height = self.height // 2
        print(width, height)
        f1 = tk.LabelFrame(self.window, text='已开课程', width=width - 15, height=height)
        f2 = tk.LabelFrame(self.window, text='课程详情', width=width - 15, height=height)
        f3 = tk.LabelFrame(self.window, text='开启课程', width=width - 15, height=height - 10)
        f4 = tk.LabelFrame(self.window, text='其他', width=width - 15, height=height - 10)
        detail_info_dict = {}
        mapped_dict = {}
        get_class_id = 0

        # # 两个listbox的操作
        create_class_info = tk.Listbox(f1, height=self.height)
        detail_listbox = tk.Listbox(f2, height=self.height)

        def do_choice(_, self):

            def get_order_count(self, class_id):
                self.us.send_to_server('GET /orderlist/getordercount?class_id=%s SOCKET' % class_id)
                coder, order_count = self.us.recv_from_server().split(':')
                if coder == '200':
                    return order_count
                else:
                    return '-'

            nonlocal get_class_id

            index = 0
            detail_index = mapped_dict[create_class_info.curselection()[0]]  # 从mapped里去除索引对应的class_id映射
            detail_info_list = ['class_name', 'class_type', 'class_info', 'class_time', 'class_status', 'order_count']
            # _ = ['class_id', 'class_name', 'class_type', 'class_info', 'class_time', 'class_status']
            detail_desc = ['课程名称: ', '科目类型:', '课程介绍:', '上课时间: ', '课程状态:', '预约人数:']

            get_class_id = detail_index  # 选择这一条后,将全局变量的id改变方便使用
            order_count = get_order_count(self, get_class_id)
            detail_info_dict[get_class_id]['order_count'] = order_count
            detail_listbox.delete(0, len(detail_info_list))  # 每次点击都要清空一次列表内容, 避免重复显示

            for detail_key in detail_info_list:
                detail_listbox.insert(index, detail_desc[index] + str(detail_info_dict[detail_index][detail_key]))
                index += 1

        create_class_info.bind('<Double-Button-1>', lambda x: do_choice(_=x, self=self))

        def do_cancel(_, self):
            user_choice = msgbox.askquestion(title='取消开课', message='是否取消已开课程')

            if 'yes' == user_choice:
                self.us.send_to_server('GET /orderlist/classcancel?teacher_id=%s&class_id=%s socket' % (self.uid,
                                                                                                        get_class_id))
                rep_code, rep_msg = self.us.recv_from_server().split(':')
                if rep_code == '200':
                    msgbox.showinfo(MSGBOX_TITLE_ORDER, message='%s' % rep_msg)
                    detail_listbox.delete(0, 1000)
                    get_class_info()

                else:
                    msgbox.showinfo(MSGBOX_TITLE_ORDER, message='%s' % rep_msg)

            else:
                print('课程未取消')

        detail_listbox.bind('<Double-Button-1>', lambda x: do_cancel(_=x, self=self))
        # 返回主页button
        tk.Button(f4, text='回到主页', command=self.do_back).place(relwidth=1, relheight=1)

        # =======f3LabelFrame=======
        LB_RELX = .05
        E_RELX = .25

        # 把label添加到f3的窗口中
        tk.Label(f3, text='课程名称', font=self.font).place(relx=LB_RELX, rely=.1)
        tk.Label(f3, text='课程类型', font=self.font).place(relx=LB_RELX, rely=.25)
        tk.Label(f3, text='课程时间', font=self.font).place(relx=LB_RELX, rely=.4)
        tk.Label(f3, text='课程介绍', font=self.font).place(relx=LB_RELX, rely=.55)

        # 把输入框添加到窗口中
        classname = tk.Entry(f3, width=30, relief=tk.FLAT)
        classtype = tk.Entry(f3, width=30, relief=tk.FLAT)
        classdate = ttk.Combobox(f3,
                                 values=[((date.today()+timedelta(days=1)) + timedelta(days=i)).strftime('%Y%m%d')
                                         for i in range(7)],
                                 width=10)
        classtime = ttk.Combobox(f3,
                                 values=(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20),
                                 width=5)
        classdate.current(newindex=0)
        classtime.current(newindex=0)
        classdesc = tk.Text(f3, width=30, height=3, relief=tk.FLAT)

        classname.place(relx=E_RELX, rely=.1)
        classtype.place(relx=E_RELX, rely=.25)
        classdate.place(relx=E_RELX, rely=.4)
        classtime.place(relx=E_RELX+.25, rely=.4)
        classdesc.place(relx=E_RELX, rely=.55)

        # f3按钮的两个方法
        def do_commit():
            try:
                assert not classname.get().strip() == ''
            except AssertionError:
                msgbox.showinfo(title='开通结果', message='课程名称不能为空！')
                print('课程名称不能为空')
            else:
                try:
                    assert not classtype.get().strip() == ''
                except AssertionError:
                    msgbox.showinfo(title='开通结果', message='课程类型不能为空！')
                    print('课程类型不能为空')
                else:
                    try:
                        assert not classdate.get().strip() == ''
                    except AssertionError:
                        msgbox.showinfo(title='开通结果', message='上课日期不能为空！')
                    else:
                        try:
                            assert not classtime.get().strip() == ''
                        except AssertionError:
                            msgbox.showinfo(title='开通结果', message='上课时间不能为空！')
                            print('上课时间不能为空')
                        else:
                            try:
                                assert not classdesc.get(1.0, tk.END).strip() == ''
                            except AssertionError:
                                msgbox.showinfo(title='开通结果', message='课程描述不能为空！')
                                print('课程描述不能为空')
                            else:
                                try:
                                    self.us.send_to_server('GET /orderlist/class_add?'
                                                           'class_name=%s&'
                                                           'class_type=%s&'
                                                           'class_info=%s&'
                                                           'class_date=%d&'
                                                           'class_time=%d&'
                                                           'teacher_id=%s '
                                                           'SOCKET'
                                                           % (classname.get().replace(' ', '').strip(),
                                                              classtype.get().replace(' ', '').strip(),
                                                              classdesc.get(1.0, tk.END).replace(' ', '').strip(),
                                                              int(classdate.get()),
                                                              int(classtime.get()),
                                                              self.uid))
                                except Exception as e:
                                    print('开通失败, 错误原因:', e)
                                    msgbox.showerror(title='开通失败通知', message='开通失败，请检查输入内容')
                                else:
                                    coder, msgr = self.us.recv_from_server().split(':')

                                    if coder == '200':
                                        msgbox.showinfo(title='开通结果', message=msgr)
                                        get_class_info()
                                    else:
                                        msgbox.showerror(title='开通失败', message=msgr)

        # f3里的清空按钮，不着急实现
        def do_clear():
            pass

        # 把按钮添加到窗口中
        tk.Button(f3, text='添加课程', height=1, command=lambda : do_commit()).place(relx=.2, rely=.82)
        tk.Button(f3, text='清空内容', height=1, command=lambda : do_clear()).place(relx=0.6, rely=.82)

        create_class_info.place(relx=0, rely=0, relwidth=1, relheight=1)
        detail_listbox.place(relx=0, rely=0, relwidth=1, relheight=1)

        # 获取开课信息
        def get_class_info():
            a = create_class_info.delete(0, 10000)
            print(a)
            self.us.send_to_server('GET /orderlist/tinfo?teacher_id=%s socket' % self.uid)
            order_page_json = self.us.recv_from_server()
            teacher_classes = json.loads(order_page_json)

            print(teacher_classes)

            index = 0

            _ = ['class_id', 'class_name', 'class_type', 'class_info', 'class_time', 'class_status']
            for class_info in teacher_classes:

                create_class_info.insert(index, '课程: %s  上课时间:%s点  课程状态: %s'
                                         % (class_info['class_name'],
                                            class_info['class_time'],
                                            '开启' if class_info['class_status'] == 1 else '关闭'))

                detail_info_dict[class_info['class_id']] = class_info

                mapped_dict[index] = class_info['class_id']

                index += 1

        get_class_info()
        f1.grid(row=0, column=0, padx=10)
        f2.grid(row=0, column=1)
        f3.grid(row=1, column=0)
        f4.grid(row=1, column=1)

        self.window.mainloop()

    def do_back(self):
        self.window.destroy()
        home_page = HomePage(self.uname, self.uid)
        home_page.create_page()


if __name__ == '__main__':
    home = IndexPage()
    home.create_page()# 开启主页
    chat = ReplyComment('wang', '2')
    height = 450
    width = 750
    chat.create_page()
